/**
 * @ author: 汪孟苹
 */
define(["jquery","bootstrap","bbcare","comm/datatable/datatable"],function($,bootstrap,$bb,$datatable){
    var servers = {};
    var URL = $bb.baseUrl("followapp");

    /**
     * 获取复选框value 
     */
    var getValueCheckbox = function(name,arg){
        var value = [];
        $("#datatableForm input[type='checkbox'][name='"+ name +"']:checked").each(function(){
            value.push($(this).val());
        });
        if( value.length > 0 ) arg[name] = value;
        return arg;
    }

    /**
     * 入参
     */
    var inParams = function(args){
        var params = $bb.getPageParams();
        var arg = {
            "args": JSON.stringify(args),
            "flag":"8",
            "busiTypeList":params.busiTypeList,
            "queueId":params.queueId,
            "schemeId":params.schemeId,
            "hisNo":$.trim( $("#datatableForm input[name=hisNo]").val() ),
            "userName":$.trim( $("#datatableForm input[name=userName]").val() ),
            "phoneNo":$.trim( $("#datatableForm input[name=phoneNo]").val() ),
            "gender": $("#datatableForm input[name=gender]:checked").val(),
            "beginDate":$("#datatableForm input[name=beginDate]").val(),
            "endDate":$("#datatableForm input[name=endDate]").val()
        };
        if( params.kind=="1" || params.kind=="2" || params.kind=="3" || params.kind=="4" ){
            $.extend(arg,{
                "manageBeginDate":$("#datatableForm input[name=manageBeginDate]").val(),
                "manageEndDate":$("#datatableForm input[name=manageEndDate]").val(),
                "currentStatus":$("#datatableForm input[name=currentStatus]").val(),
            });
        }else if( params.kind=="5" || params.kind=="6" || params.kind=="7" || params.kind=="8" ){
            var $seqDom = $("#datatableForm select[name=seqFrom]").find("option:selected");
            var $seqTo = $("#datatableForm select[name=seqTo]").find("option:selected");
            $.extend(arg,{
                "seqFrom":$seqDom.attr("data-startDay"),
                "seqTo":$seqTo.attr("data-endDay"),
                "checkFrom":$("#datatableForm input[name=checkFrom]").val(),
                "checkTo":$("#datatableForm input[name=checkTo]").val(),
                "lostFrom":$("#datatableForm input[name=lostFrom]").val(),
                "lostTo":$("#datatableForm input[name=lostTo]").val(),
                "health":$("#datatableForm select[name=heath]").val(),
                "createAuthor":$("#datatableForm select[name=createAuthor]").val(),
            });
        }
        if( params.kind == "1" ){
            $.extend(arg,{"foodConversionAge":$("#datatableForm input[name=foodConversionAge]").val()});
            getValueCheckbox("birthHistorys",arg);
        }else if( params.kind == "2" ){
            $.extend(arg,{
                "foodIronAge":$("#datatableForm input[name=foodIronAge]").val(),
                "breastfeeding":$("#datatableForm input[name=breastfeeding]").val(),
                "isIron":$("#datatableForm input[name=isIron]:checked").val(),
            });
        }else if( params.kind == "3" ){
            $.extend(arg,{
                "isVitd":$("#datatableForm input[name=isVitd]:checked").val(),
                "bloodCalcium":$("#datatableForm input[name=bloodCalcium]").val(),
                "bloodPhosphorus":$("#datatableForm input[name=bloodPhosphorus]").val(),
                "bloodAKP":$("#datatableForm input[name=bloodAKP]").val(),
                "bloodOHD":$("#datatableForm input[name=bloodOHD]").val(),
            });
            getValueCheckbox("signs",arg);
        }else if( params.kind == "4" ){
            $.extend(arg,{
                "obesityScore":$("#datatableForm input[name=obesityScore]:checked").val(),
                "obesityReason":$("#datatableForm input[name=obesityReason]:checked").val(),
            });
        }else if( params.kind == "5" ){
            $.extend(arg,{
                "leftVision":$("#datatableForm input[name=leftVision]").val(),
                "rightVision":$("#datatableForm input[name=rightVision]").val(),
            });
            getValueCheckbox("highRiskReasons",arg);
            getValueCheckbox("eyeAppearance",arg);
            getValueCheckbox("conjunctiva",arg);
            getValueCheckbox("pupil",arg);
        }else if( params.kind == "6" ){
            getValueCheckbox("auricularAppearances",arg);
        }else if( params.kind == "7" ){
            getValueCheckbox("dentalCaries",arg);
            getValueCheckbox("dentalExaminations",arg);
        }else if( params.kind == "8" ){
        }
        return JSON.stringify({ data: arg });
    }
    /**
     * 出参
     */
    var outParams = function(data){
        return data.rows;
    }
    /**
     * columns
     */
    var columnsHisNo = function(e){
        return e.hisNo ? e.hisNo : e.hisNo1 ? e.hisNo1 : e.hisNo2 ? e.hisNo2 : "-";
    }
    var columnsGender = function(e){
        return e.gender == 'F' ? '女' : e.gender == 'M' ? '男' : '未知';
    }
    var columnsData = function(){
        var columnsArr = [
            {"data":columnsHisNo},
            {"data":'userName'},
            {"data":columnsGender},
            {"data":'phoneNo'},
            {"data":'birthday'},
        ];
        var params = $bb.getPageParams();
        if( params.kind == "1" ){
            var arr1 = [
                {"data":'startManageDate'},
                {"data":'foodConversionAge'},
            ];
            columnsArr = columnsArr.concat(arr1);
        }else if( params.kind == "2" ){
            var arr2 = [
                {"data":'startManageDate'},
                {"data":'breastfeeding'},
                {"data":'isIron'}
            ];
            columnsArr = columnsArr.concat(arr2);
        }else if( params.kind == "3" ){
            var arr3 = [
                {"data":'startManageDate'},
                {"data":'bloodCalcium'},
                {"data":'bloodPhosphorus'},
                {"data":'bloodAKP'},
                {"data":'bloodOHD'},
                {"data":'isVitd'},
                {"data":'sign'},
            ];
            columnsArr = columnsArr.concat(arr3);
        }else if( params.kind == "4" ){
            var arr4 = [
                {"data":'startManageDate'},
                {"data":'obesityScore'},
                {"data":'obesityReason'}
            ];
            columnsArr = columnsArr.concat(arr4);
        }else if( params.kind == "5" ){
            var arr4 = [
                {
                    "data": null,
                    "className":"progress-interview"
                },
                {"data":'leftVision'},
                {"data":'rightVision'}
            ];
            columnsArr = columnsArr.concat(arr4);
        }else if( params.kind == "6" ){
            var arr4 = [
                {
                    "data": null,
                    "className":"progress-interview"
                },
                {"data":'auricularAppearance'}
            ];
            columnsArr = columnsArr.concat(arr4);
        }else if( params.kind == "7" ){
            var arr4 = [
                {
                    "data": null,
                    "className":"progress-interview"
                },
                {"data":'dentalCaries'},
                {"data":'dentalExamination'}
            ];
            columnsArr = columnsArr.concat(arr4);
        }else if( params.kind == "8" ){
            var arr4 = [
                {
                    "data": null,
                    "className":"progress-interview"
                }
            ];
            columnsArr = columnsArr.concat(arr4);
        }
        columnsArr.push({
            "data": null,
            "className":"operate"
        });
        return columnsArr;
    }
    /**
     * 行绘制回调函数
     */
    var rowCallback = function(row, data, index) {
        // 进度
        var h1 = "";
        var len = data.nodeStatusArr.length;
        var width = parseInt(100 / len) + '%';
        for (var i = 0; i < len; i++) {
            var status = data.nodeStatusArr[i];
            var obj = {};
            if( status == '0' ){                   // 未开始
                obj.className = "progress-notstart";
                obj.title = "未开始";
            }else if( status == '1' ){             // 已完成
                obj.className = "progress-finish";
                obj.title = "已完成";
            }else if( status == '2' ){             // 过期（未开始）
                obj.className = "progress-overdue";
                obj.title = "过期";
            }else if( status == '3' ){             // 过期（补填）
                obj.className = "progress-fill";
                obj.title = "补填";
            }else if( status == '4' ){             // 未完成（部分任务填写）
                obj.className = "progress-nofinish";
                obj.title = "未完成";
            }
            h1 += '<div style="width:'+width+'"><i class="'+obj.className+'" data-toggle="tooltip" data-placement="top" title="'+obj.title+'"></i></div>';
        }
        var html = '<div class="progress-wrap">'+ h1 +'</div>';
        $('td.progress-interview', row).html(html);
        // 操作
        var h2 = '<div class="operate-box"><i class="fa fa-pencil-square-o color-blue" data-toggle="tooltip" data-placement="top" title="编辑"></i></div>';
        $('td.operate', row).html(h2);
        $("td.operate .operate-box i.color-blue",row).unbind("click");
        $("td.operate .operate-box i.color-blue",row).click(function(){
            var params = $bb.getPageParams();
            $bb.openPage("bch_user",{"busiTypeList":params.busiTypeList,"userId":data.userId});
        });
    };
    /**
     * 初始化完成之后的回调函数
     */
    var initComplete = function(setting,json){
        var id = $(".layout-bottom table").attr("id");
        $("#" + id).prev("div.row").remove();
        // 搜索 
        $("#serchBtn").click(function(){
            $datatable.table.api().ajax.reload();  // 出发dt的重新加载数据的方法
            var args = $datatable.table.api().ajax.params();   //获取dt请求参数 
        });
        // 初始化所有工具提示
        $(function(){$("[data-toggle='tooltip']").tooltip();});
    }
    /**
     * 获取datatable里的options
     */
    servers.getOptions = function(){
        var sessionId = $bb.getSessionStorage("sessionId");
        var options = {
            "ajax": {
                "url": URL + "ctrl/ptmanage/qryUserListTable?sessionId=" + sessionId,
                "data": inParams,
                "dataSrc": outParams
            },
            "columns": columnsData(),
            "rowCallback": rowCallback,
            "initComplete": initComplete,
        };
        return options;
    }

    return servers;
});